import { ref } from 'vue'
import { defineStore } from 'pinia'
import type { LocationQuery, RouteRecordRaw } from 'vue-router'
import type { IDoLoginProps } from '../interface/auth'
import type { IUserBase } from '@/interface/types/idt/user.interface'
import type { IMenuItem } from '@/interface/types/pow/menu.interface'
import { AccountService } from '@/services/api/account.service'
import { menuMachining } from '@/router/tools'

export const AuthStore = defineStore(
  'AuthState',
  () => {
    const access_token = ref('')
    const refresh_token = ref('')
    const user = ref<IUserBase>({})
    const allmenus = ref<IMenuItem[]>([])
    const menus = ref<RouteRecordRaw[]>([])
    const perms = ref<IMenuItem[]>([])
    const navs = ref<
      {
        path: string
        query?: LocationQuery
      }[]
    >([
      {
        path: '/wel',
      },
    ])
    const login = ref(false)

    const setNav = (
      data: { path: string; query?: LocationQuery } | { path: string; query?: LocationQuery }[],
    ) => {
      if (Array.isArray(data)) {
        navs.value = [...data]
        return
      }

      if (!navs.value.map((item) => item.path).includes(data.path)) {
        navs.value = [...navs.value, data]
      } else {
        navs.value = navs.value.map((item) => {
          if (item.path == data.path) {
            return data
          }
          return item
        })
      }
    }

    // 用户登录
    const doLogin = async (data: IDoLoginProps): Promise<boolean> => {
      try {
        const res = await AccountService.doLoginApi(data)
        login.value = true
        access_token.value = res.access_token
        refresh_token.value = res.refresh_token

        localStorage.setItem('access_token', res.access_token)
        localStorage.setItem('refresh_token', res.refresh_token)
        return true
      } catch (error) {
        console.log(error)
        return false
      }
    }

    const doLogout = async (): Promise<boolean> => {
      try {
        const res = await AccountService.doLogoutApi()
        login.value = false
        access_token.value = ''
        refresh_token.value = ''

        localStorage.setItem('access_token', '')
        localStorage.setItem('refresh_token', '')
        return true
      } catch (error) {
        console.log(error)
        return false
      }
    }

    // 设置路由信息
    const updatePerms = async (): Promise<boolean> => {
      try {
        const res = await AccountService.getPermsApi()
        user.value = res.user || {}
        allmenus.value = [...(res?.menus || [])]
        menus.value = menuMachining(res.menus || [])
        perms.value = res?.perms || []

        login.value = true
        return true
      } catch (error) {
        console.log(error)
        return false
      }
    }

    return {
      access_token,
      refresh_token,
      user,
      allmenus,
      menus,
      perms,
      navs,
      login,
      setNav,
      doLogin,
      doLogout,
      updatePerms,
    }
  },
  {
    persist: {
      storage: localStorage,
      pick: ['navs', 'user', 'access_token', 'refresh_token', 'menus', 'perms'],
    },
  },
)
